package com.yolo.yolorpc.serializer;


import java.io.*;

/**
 * @Program: RPC
 * @description: Jdk序列化器
 * @author: yolo
 * @create: 2025-04-21 16:28
 **/
public class JdkSerializer implements Serializer{

    /**
     * @descript: 序列化
     * @author: yolo
     * @date: 2025/4/21 16:28
     * @param object
     * @return: Byte
     **/
    @Override
    public <T> byte[] serialize(T object) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        return outputStream.toByteArray();
    }

    /**
     * @descript: 反序列化
     * @author: yolo
     * @date: 2025/4/21 16:29
     * @param bytes
     * @param type
     * @return: T
     **/
    @Override
    public <T> T deserialize(byte[] bytes, Class<T> type) throws IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        try (ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            return (T) objectInputStream.readObject();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
